﻿/**
  KCAKCAK   CAKCAKC   AK      CA
 AK        KC     CA  AK    AK
CA         KC     CA  AK  KC
CA         KCAKCAKCA  AKCA
CA         KC     CA  AK  KC
 AK        KC     CA  AK    AK
  KCAKCAK  KC     CA  AK      CA

_________________________________________________________________
 China ataca Kamchatka - copyright 2007(c) Ruben Sainz de la Maza
 
	@class: 	Lobby
	@vertion: 	0.1
	@date:		27/02/08
				
	@language: 	ActionScript 3.0
	@author:	Ruben Sainz de la Maza
			
**/


package com.conelmate.cak.screens
{
	import com.conelmate.util.Trace;
	import com.conelmate.nc.Connect;
	import com.conelmate.nc.AbstractProxyClient;
	import com.conelmate.cak.screens.LobbyRoom;
	
	import fl.containers.ScrollPane;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.display.MovieClip;
	import fl.controls.Button;
	import flash.events.Event;
	
	

	public class Lobby extends AbstractProxyClient
	{	
		static	public	const 	CONNECTED		:String = "CONNECTED";	
		static	public	const 	CLOSED			:String = "CLOSED";
		static	public	const 	FAILED			:String = "FAILED";	
		
		static internal var		_INSTANCE		:Lobby;			//instancia de esta clase (singleton)
						var 	_objConnect		:Connect;		//ref a la clase de coneccion al servidor FMS
						
				private var 	_MC				:MovieClip;		//contenedor
				private var 	_mcLobby		:MovieClip;		//attach library lobby/mcLobby
				private var		_compSP			:ScrollPane;
				private var		_container		:Sprite;
				private var 	_strNick		:String;
				private var		_arrRooms		:Array;
				private var		_txtLobby;
		
		
//_________________________________________________________________________________ Constructor		
		public function Lobby(enforcer:SingletonEnforcer)
		{
			_isTrace = true;
			mTrace("#Lobby# constructor");
		}


//_________________________________________________________________________________ Public Methods

		/**
		 * singleton
		 * devolver una instancia de la clase
		 */	
		public static function getInstance():Lobby
		{
			if(Lobby._INSTANCE == null) Lobby._INSTANCE = new Lobby(new SingletonEnforcer());
			return Lobby._INSTANCE;
		}
		
		
		/**
		 * inicializar
		 */		
		public function init(pContainer, p_strNick:String):void
		{
			mTrace("#Lobby# init");
			initializeProxy("Lobby"); //se ejecuta en AbstractProxyClient
			
			_arrRooms = new Array();
			_container = new Sprite();			
			_strNick = p_strNick;		
			
			_objConnect = Connect.getInstance();
			_objConnect.addEventListener(Connect.CONNECTED, onConnect);
			_objConnect.addEventListener(Connect.CLOSED, 	onClosed);
			
			_MC = pContainer;
			_mcLobby = _MC.mcLobby;	//attach library screens/lobby/mcLobby
			_mcLobby.visible = true;
			
			_compSP = new ScrollPane();
            _compSP.move(0,19);
            _compSP.setSize(490,300);
            _compSP.source = _container;
			
			_mcLobby.bAdd.addEventListener(MouseEvent.CLICK, serverPushUser);
			_mcLobby.bRemove.addEventListener(MouseEvent.CLICK, serverPopUser);
		//	_mcLobby.bReconnect.addEventListener(MouseEvent.CLICK, reconnect);
			_mcLobby.bCreate.addEventListener(MouseEvent.CLICK, serverCreateNewRoom);
		
            _mcLobby.addChild(_compSP);
			
			_mcLobby.iArea.text = "Sala";
			_txtLobby = _mcLobby.txtLobby;

			_objProxyClient.serverCall("Rooms", _responder, "getRooms", _strNick);

		//SIMULAR EL ROOM
		//	_arrRooms.push("x")
		//	addRoom({room:"juego", users:2, maxUsers:5, status:"OJO", type:"tipo"})
		}
		
		
		/**
		 * destruir objetos y variables
		 */	
		public function destroy():void
		{
			mTrace("#Lobby# destroy");
			finalizeProxy("Lobby");
			Lobby._INSTANCE = null;
		}



//_________________________________________________________________________________ FROM Server


		/**
		 * actualizar la cantidad de usuarios en el Lobby
		 * desde server Rooms.prototype.pushUser
		 * 				Rooms.prototype.popUser
		 */		
		public function usersInRoom(p_Users:Number):void
		{
			mTrace("#Lobby# usersInRoom " + p_Users);
			_txtLobby.text = "Lobby: " + p_Users;
			
		//	application.objRooms[_strRoom].colors = {NEGRO:false, ROJO:false, AMARILLO:false, AZUL:false, BLANCO:false, VERDE:false};

		}
		
		
		/**
		 * crear una nueva sala en el listado de rooms
		 * desde server Rooms.prototype.pushUser
		 */		
		public function addRoom(p_Room:Object):void
		{
			mTrace("#Lobby# addRoom " + _container);
			var r = p_Room;
			var room = new LobbyRoom();
			
			room.container	= _container;
			room.posy		= _arrRooms.length * 20;
			room.roomName	= r.room;
			room.background	= _arrRooms.length % 2;
			room.users		= r.users;
			room.maxUsers	= r.maxUsers;
			room.status		= r.status;
			room.type		= r.type;
			room.init();
			_arrRooms.push(room);
			
		//	application.objRooms[_strRoom].colors = {NEGRO:false, ROJO:false, AMARILLO:false, AZUL:false, BLANCO:false, VERDE:false};

		}

		/**
		 * modificar la data de una sala
		 * desde Rooms.prototype.pushUser
		 */		
		public function refreshRoom(p_Room:Object):void
		{
			mTrace("#Lobby# refreshRoom");
		}
		
		
		/**
		 * llamada desde Rooms.prototype.getRooms
		 */		
		public function setRooms(p_obj:Object):void
		{
			mTrace("#Lobby# setRooms");
			for(var i in p_obj) if(i != "lobby") addRoom(p_obj[i]);
		}		

		
		public function deleteRoom():void
		{
		}
		
//_________________________________________________________________________________ Private Methods

		/**
		 * ingresar a una sala de juegos
		 */		
		private function serverPushUser(e:MouseEvent):void
		{
			mTrace("#Lobby# serverPushUser");
			_objProxyClient.serverCall("Rooms", _responder, "pushUser", _strNick, _mcLobby.iArea.text);
		}


		/**
		 * salir de una sala y volver al lobby
		 */		
		private function serverPopUser(e:MouseEvent):void
		{
			_objProxyClient.serverCall("Rooms", _responder, "popUser", _strNick);
		}
		

		/**
		 * crear una nueva sala de juegos
		 */		
		private function serverCreateNewRoom(e:MouseEvent):void
		{
			//p_strRoom, p_strNick, p_maxUsers, p_type)
			_objProxyClient.serverCall("Rooms", _responder, "addRoom", _mcLobby.iArea.text, _strNick, _mcLobby.iUsers.text, _mcLobby.iTipo.text);
		}
		
		
	/*	private function reconnect(e:MouseEvent):void
		{
			var o:Object = new Object;
			o.strNick = _strNick;			
			_objConnect.arguments = o;

			_objConnect.init();
		}*/
		
		
		/**
		 * al conectar
		 */		
		private function onConnect(e:Event):void
		{
			mTrace("#Lobby# onConnect");
		}
		

		/**
		 * al cerrarse la coneccion
		 */		
		private function onClosed(e:Event):void
		{
			mTrace("#Lobby# onClosed");
		}
		

		/**
		 * evento respuesta del server luego de llamar un metodo desde el cliente
		 * ej: _objProxyClient.serverCall("Rooms", _responder, "pushUser", _strNick, _mcLobby.iArea.text);
		 */		
		override public function onBack(o:Object):void
		{
			if(o != null){			
				var func:String = o.func;
				var room:String	= o.room;
				var success:Boolean = o.success;
				
				
				for(var i in o) trace("..... " +i+" "+o[i]);
				
				var msg:String;
				if(o.msg) msg = "*" + o.msg;
				mTrace("#Lobby# onBack " + func + " " + room + ":" + success + " " + msg);
				
				if(func == "addRoom" && success) addRoom({room:room, users:o.users, maxUsers:o.maxUsers, status:o.status, type:o.type})
			}
		}

	}
}

internal class SingletonEnforcer{}
